<?php
// +----------------------------------------------------------------------
// | ThinkCMF [ WE CAN DO IT MORE SIMPLE ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2018 http://www.thinkcmf.com All rights reserved.
// +----------------------------------------------------------------------
// | Released under the MIT License.
// +----------------------------------------------------------------------
// | Author: 老猫 <thinkcmf@126.com>
// +----------------------------------------------------------------------

namespace app\api\controller;
use think\Db;
class CourseController extends BaseController
{

	/**
	*课程-查看详情页面
	*
	**/
	public function details()
	{
		$course_id = $this->request->param('course_id', '');
		if(empty($course_id)){
	       return return_msg(2002, '参数有误，非法请求');
		}

		//开始查找课程
		$courseModel = new \app\home\model\CourseModel();
    	$coulabelModel = new \app\home\model\CourseLabelModel();
        $couageModel = new \app\home\model\CourseAgeModel();
        $cousubjectModel = new \app\home\model\CourseSubjectModel();

        $str = 'id, title, long_title, inventory_number, sell_money, original_money, basic_number, sales_number, zt_logo, js_logo, buy_notice, start_time, end_time, explain';
        $info = $courseModel->getCourseInfoDetails($course_id, $str);
        if(empty($info))
        {
        	return return_msg(2003, '该课程已下架');
        }

    	$info['label'] = $coulabelModel->getCourseLabelList($info['id'], 'id,label');
    	$info['zt_logo'] = json_decode($info['zt_logo']);//'/upload/'.$info['zt_logo']
    	foreach ($info['zt_logo'] as $key => $value) {
    		$zj_logo[] = json_img_add_url('/upload/'.$value);
    	}
    	$info['zt_logo'] = $zj_logo;


    	$info['js_logo'] = json_decode($info['js_logo']);
    	foreach ($info['js_logo'] as $key => $value) {
    		$js_logo[] = json_img_add_url('/upload/'.$value);
    	}
    	$info['js_logo'] = $js_logo;

    	$info['buy_notice'] = json_img_add_url(htmlspecialchars_decode($info['buy_notice']));
        
    	return return_msg(200, '', $info);
	}



	/**
	*购买课程页面
	*
	**/
	public function addOrders()
	{
		$course_id = $this->request->param('course_id', '');
		if(empty($course_id)){
	       return return_msg(2004, '参数有误，非法请求');
		}

		//开始查找课程
		$courseModel = new \app\home\model\CourseModel();
    	$coulabelModel = new \app\home\model\CourseLabelModel();
        $couageModel = new \app\home\model\CourseAgeModel();
        $cousubjectModel = new \app\home\model\CourseSubjectModel();

        $str = 'id, title, long_title, inventory_number, sell_money, original_money, basic_number, sales_number, xt_logo, start_time, end_time, explain,status, attend_type, activate_method, activate_time,refund';
        $info = $courseModel->getCourseInfoDetails($course_id, $str);
        if(empty($info)||($info['status'] != 1))
        {
        	 return return_msg(2005, '该课程已下架');

        }

        //课程结束时间，对比当前时间
        $time = time();
        $start_time = strtotime($info['start_time']);
        $end_time = strtotime($info['end_time']);

        //判断课程是否开始售卖时间
        if(($time > $end_time) || ($time < $start_time))
        {
 			return return_msg(2006, '该课程不在售卖期');
        }

        $info['xt_logo'] = json_img_add_url('/upload/'.$info['xt_logo']);

        //查找用户最近的一次订单收货信息
        $member_id = $this->member_id;
        $orderModel = new \app\home\model\OrdersModel();
        $order_info = $orderModel->getMemberOrderAddtimeAsc($member_id, 'recipients, mobile, province, city, district, site');
        if(!empty($order_info))
        {
            $info['recipients'] = $order_info['recipients'];
            $info['mobile'] = $order_info['mobile'];
            $info['province'] = $order_info['province'];
            $info['city'] = $order_info['city'];
            $info['district'] = $order_info['district'];
            $info['site'] = $order_info['site'];
        }
        
        return return_msg(200, '', $info);
	}



	/**
	*
	*课程 - 生成订单,拉起支付
	**/
	public function payCourse()
	{
		//接收数据，检测数据
        $member_id = $this->member_id;
		$data = $this->request->param();

        //检测参数
        $validate = new \app\api\validate\CourseValidate();
        if(!$validate->scene('pay')->check($data))
        {
            return return_msg(2008, $validate->getError());
        }

        //判断手机号
        if(!cmf_check_mobile($data['mobile']))
        {
            return return_msg(20051, '请输入正确的手机号码');
        }

        //查找课程价格
        $courseModel = new \app\home\model\CourseModel();

        $str = 'id, title, sell_money, inventory_number, start_time, end_time, status';
        $cinfo = $courseModel->getCourseInfoDetails($data['course_id'], $str);
        if(empty($cinfo)||($cinfo['status'] != 1))
        {
             return return_msg(2005, '该课程已下架');

        }

        //课程结束时间，对比当前时间
        $time = time();
        $start_time = strtotime($cinfo['start_time']);
        $end_time = strtotime($cinfo['end_time']);

        //判断课程是否开始售卖时间
        if(($time > $end_time) || ($time < $start_time))
        {
            return return_msg(2006, '该课程不在售卖期');
        }

        //课程库存
        if($cinfo['inventory_number'] <= 0)
        {
            return return_msg(2006, '该课程已售罄');
        }


        //开始生成订单，并拉起微信支付
        $orderModel = new \app\home\model\OrdersModel();

        //生成订单编号
        $order_number = date('YmdHis');
        $order_number .= $this->random_string(6);
        
        $add_data = [
            'member_id' => $member_id,
            'order_number' => $order_number,
            'course_id' => $data['course_id'],
            'recipients' => $data['recipients'],
            'mobile' => $data['mobile'],
            'province' => $data['province'],
            'city' => $data['city'],
            'district' => $data['district'],
            'site' => $data['site'],
            'pay_money' => $cinfo['sell_money'],//售价
            'pay_number' => 1,
        ];


        $res = $orderModel->addMemberOrders($add_data);
        if(empty($res))
        {
            return return_msg(2009, '生成课程订单失败，系统错误');
        }

        //统一下单
        $body = '购买课程：'.$cinfo['title'];
        $out_trade_no = $add_data['order_number'];
        $total_fee = $cinfo['sell_money'] * 100;
        $notify_url = WEB_URL.'/api/pay_back';

        $wx = new WxController();
        $order = $wx->getPrePayOrder($body, $out_trade_no, $total_fee, $notify_url);
        if ($order['prepay_id']){//判断返回参数中是否有prepay_id
                    
            $order1 = $wx->getOrder($order['prepay_id']);//执行二次签名返回参数
            $order1['order_id'] = $res;
            return return_msg(200, '', $order1);
        } else {
            return return_msg(2010, '', $order['err_code_des']);
        }

	}



    /**
    *
    *查看上课方式
    **/
    public function lookCourseWay()
    {
        $member_id = $this->member_id;
        $course_id = $this->request->param('course_id', '');
        $order_id = $this->request->param('order_id', '');
        if(empty($course_id)){
           return return_msg(2010, '课程ID不能为空');
        }


        //开始查找课程
        $courseModel = new \app\home\model\CourseModel();
        $orderModel = new \app\home\model\OrdersModel();
        $coursecodeModel = new \app\home\model\CourseCodeModel();


        $str = 'id, title, attend_type, buy_notice, status,activate_method, activate_time';
        $info = $courseModel->getCourseInfoDetails($course_id, $str);
        if(empty($info))
        {

            return return_msg(2011, '该课程已下架');
        }
        $info['buy_notice'] = json_img_add_url(htmlspecialchars_decode($info['buy_notice']));

        //如果有订单ID
        if(!empty($order_id))
        {
            $where = [
                ['member_id', '=', $member_id],
                ['order_id', '=', $order_id],
                ['status', 'in', [1,2,3,4,5]],
            ];

            $oinfo = $orderModel->memberOrderInfo($where);
            
            if(empty($oinfo))
            {
                return return_msg(2011, '不存在的订单信息，请确认后操作');
            }

            /*if(!empty($oinfo['dispatch_time']))
            {
                $info['dispatch_time'] = strtotime($oinfo['dispatch_time']);
                $info['arrive_time'] = strtotime($oinfo['dispatch_time']) - time() + (86400 * 10);
            }*/
            $info['arrive_time'] = $oinfo['activate_time'];
            

            //查找兑换码
            if(!empty($oinfo['course_code_id']))
            {
                $code_info = $coursecodeModel->getOrderCodeInfo($oinfo['course_code_id'], 'id, code_name');
                $info['code_name'] = $code_info['code_name'];
            }
        }
        return return_msg(200, '', $info);
    }






    public function random_string($len = 6)
    {
        $chars    = [
            "1","2","3","4","5","6","7","8","9","0"
        ];
        $charsLen = count($chars) - 1;
        shuffle($chars);    // 将数组打乱
        $output = "";
        for ($i = 0; $i < $len; $i++) {
            $output .= $chars[mt_rand(0, $charsLen)];
        }
        return $output;
    }
}